from django.contrib.auth.hashers import make_password
from rest_framework import serializers
from .models import *


# 1. 分类序列化器
class UserSer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = '__all__'

    # 1. 验证函数---对数据进一步验证和处理
    def validate(self, attrs):

        # print(attrs, '-----------------00077777')
        name = attrs['name']
        pwd = attrs['pwd']   # 密码
        pwd2 = attrs['pwd2']  # 确认密码

        # 1.1 判断用户名是否已注册
        user_li = User.objects.filter(name=name)

        if user_li:
            raise serializers.ValidationError('用户名已存在')

        # 1.2 判断两次密码是否一致
        if pwd2 != pwd:
            raise serializers.ValidationError('两次密码不一致，请重新输入')

        # 1.3 判断密码长度 是否为6位
        if len(pwd) != 6:
            raise serializers.ValidationError('密码长度必须为6位')

        # 1.4 密码加密
        attrs['pwd'] = make_password(pwd)
        attrs['pwd2'] = attrs['pwd']

        return attrs



